package io.gitbub.protobuf;

import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import com.google.protobuf.InvalidProtocolBufferException;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        useProtobuf();
    }
    /**
     * 简单使用
     */
    public void useProtobuf() {
        PersonProto.Person.Builder builder = PersonProto.Person.newBuilder();
        builder.setId(10086);
        builder.setName("kavin");
        builder.setEmail("kavin_tian@163.com");
        builder.setPhone("10086");

        PersonProto.Person person = builder.build();
        byte[] bytes = person.toByteArray();
        String string = Arrays.toString(bytes);
        Log.e("TAG", "person.toByteArray(): " + string);
        Log.e("TAG", "personByteArray: length: " + bytes.length);

        try {
            PersonProto.Person parseFrom = PersonProto.Person.parseFrom(bytes);
            int id = parseFrom.getId();
            String name = parseFrom.getName();
            String email = parseFrom.getEmail();
            String phone = parseFrom.getPhone();
            Log.e("TAG", "id: " + id);
            Log.e("TAG", "name: " + name);
            Log.e("TAG", "email: " + email);
            Log.e("TAG", "name: " + phone);
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
            Log.e("TAG", "parseFrom: " + e);
        }
    }
}
